<template>
  <div>
    <el-upload
      :class="{disabled:fileComputed}"
      action=""
      list-type="picture-card"
      :file-list="fileList"
      :limit="limit"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :http-request="upload"
      :on-change="handleChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条组件 -->
    <!-- <div v-if="showProgress">
      <div>上传进度：<el-progress style="width: 180px;" :percentage="percent" /></div>
    </div> -->
    <el-dialog width="600px" top="8vh" title="图片预览" :visible.sync="showDialog">
      <img width="100%" :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKID66xd4LPGqCLGxQgjaDdpnlV3PXP4Wkme', // 身份识别ID
  SecretKey: 'iFcmmZ4LPGsKcjfOuEMH1by97tRlrkQs' // 身份秘钥
})
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      // fileList: [{ name: 'food.jpeg', url: 'https://img0.baidu.com/it/u=1162805579,2770602849&fm=253&fmt=auto&app=120&f=JPEG?w=544&h=500' }
      // { name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }
      // ],
      showDialog: false,
      imgUrl: ''
      // showProgress: false,
      // percent: 0
    }
  },
  computed: {
    // 上传的文件是否到达上限
    fileComputed() {
      return this.fileList.length >= this.limit
    },
    // 判断所有图片是否上传成功
    uploadAllSuccess() {
      return this.fileList.length > 0 && this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    // 预览
    handlePreview(file) {
      // console.log(file)
      this.imgUrl = file.url
      this.showDialog = true
    },
    // 删除
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    // 上传文件
    upload(params) {
      // console.log(params)
      // 如果params里不包含file对象
      if (!params.file) return
      const imgObj = this.fileList.find(item => item.uid === params.file.uid)
      this.showProgress = true
      // 执行上传操作
      cos.putObject({
        Bucket: '13166128825-1315920988', /* 存储桶 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: +new Date() + '-' + params.file.name, /* 文件名 */
        // StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          const percent = parseInt(progressData.percent * 100)
          // this.percent = percent
          imgObj.status = 'uploading'
          imgObj.percentage = percent
        }
      }, (err, data) => {
        // console.log(err || data)
        if (err) return console.log(err)
        if (data.statusCode === 200) {
          // const fileObj = this.fileList.find(item => item.uid === params.file.uid)
          // 更新状态
          imgObj.status = 'success'
          // 修改地址
          imgObj.url = 'https://' + data.Location
        }
        // setTimeout(() => {
        //   this.showProgress = false
        //   this.percent = 0
        // }, 500)
        // console.log(data)
      })
    },
    // 无论上传成功，还是上传失败都会被调用
    handleChange(file, fileList) {
      // console.log(file, fileList)
      this.fileList = [...fileList]
    },
    // 上传前校验
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
